import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    // 用户token
    token: uni.getStorageSync('token') || '',
    // 用户手机号
    mobile: uni.getStorageSync('mobile') || '',
    // 店铺ID
    mid: uni.getStorageSync('mid') || '',
    // 用户信息
    userInfo: uni.getStorageSync('userInfo') || {},
    // 登录状态
    isLogin: !!uni.getStorageSync('token')
  },
  
  mutations: {
    // 设置token
    SET_TOKEN(state, token) {
      state.token = token
      state.isLogin = !!token
      // 同步保存到本地存储
      if (token) {
        uni.setStorageSync('token', token)
      } else {
        uni.removeStorageSync('token')
      }
    },
    
    // 设置用户手机号
    SET_MOBILE(state, mobile) {
      state.mobile = mobile
      if (mobile) {
        uni.setStorageSync('mobile', mobile)
      } else {
        uni.removeStorageSync('mobile')
      }
    },
    
    // 设置店铺ID
    SET_MID(state, mid) {
      state.mid = mid
      if (mid) {
        uni.setStorageSync('mid', mid)
      } else {
        uni.removeStorageSync('mid')
      }
    },
    
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      if (userInfo && Object.keys(userInfo).length > 0) {
        uni.setStorageSync('userInfo', userInfo)
      } else {
        uni.removeStorageSync('userInfo')
      }
    },
    
    // 清除所有用户数据（登出时使用）
    CLEAR_USER_DATA(state) {
      state.token = ''
      state.mobile = ''
      state.mid = ''
      state.userInfo = {}
      state.isLogin = false
      
      // 清除本地存储
      uni.removeStorageSync('token')
      uni.removeStorageSync('mobile')
      uni.removeStorageSync('mid')
      uni.removeStorageSync('userInfo')
    }
  },
  
  actions: {
    // 登录成功后保存token和用户信息
    loginSuccess({ commit }, { token, mobile, mid, userInfo = {} }) {
      commit('SET_TOKEN', token)
      commit('SET_MOBILE', mobile)
      commit('SET_MID', mid)
      commit('SET_USER_INFO', userInfo)
    },
    
    // 登出
    logout({ commit }) {
      commit('CLEAR_USER_DATA')
    },
    
    // 更新用户信息
    updateUserInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    }
  },
  
  getters: {
    // 获取token
    getToken: state => state.token,
    
    // 获取用户手机号
    getMobile: state => state.mobile,
    
    // 获取店铺ID
    getMid: state => state.mid,
    
    // 获取用户信息
    getUserInfo: state => state.userInfo,
    
    // 获取登录状态
    getLoginStatus: state => state.isLogin
  }
})

export default store

